<template>
  <div class="container">
    <topTitle :titleText="titleText"></topTitle>
    <div class="mainCon">
      <el-row class="editBox" style="padding-bottom: 0">
        <el-col :span="18">
          <div class="secondaryTitle secondaryTitleTheme">账号密码</div>
          <div class="itemBox">
            <span class="itemTitle">账号名：</span>
            <span class="itemValue">{{ userName }}</span>
          </div>
        </el-col>
        <el-col :span="6" class="editBoxBtn">
          <el-button
            v-show="isShowUpdate"
            type="primary"
            class="miniButColor"
            size="mini"
            @click="updatePassword()"
            ><i class="iconfont iconbianji"></i
            ><span class="opetareText">修改</span></el-button
          >
        </el-col>
        <el-col :span="24" style="margin-top: 20px">
          <el-collapse-transition>
            <changePW
              v-show="updatePass"
              :isShowUser="isShowUser"
              :isDialog="false"
              @cancelSubmitChange="cancelSubmitChange"
            ></changePW>
          </el-collapse-transition>
        </el-col>
      </el-row>

      <el-row class="editBox">
        <el-col :span="18">
          <div class="secondaryTitle secondaryTitleTheme">密保手机</div>
          <div class="itemBox">
            <span class="itemTitle">已绑定手机：</span>
            <span class="itemValue"
              >{{ phone }}，密保手机号可用于修改和找回账号密码</span
            >
          </div>
        </el-col>
        <el-col :span="6" class="editBoxBtn">
          <el-button
            v-show="isShowUpdate"
            type="primary"
            class="miniButColor"
            size="mini"
            @click="updateTelEvent()"
            ><i class="iconfont iconbianji"></i
            ><span class="opetareText">修改</span></el-button
          >
        </el-col>
        <el-col :span="24">
          <el-collapse-transition>
            <div v-show="updateTel">
              <div class="transition-box">
                <el-divider>修改密保手机号</el-divider>
                <el-form
                  :model="telForm"
                  :rules="telRule"
                  class="telForm"
                  ref="telForm"
                  label-width="120px"
                  aria-autocomplete="false"
                >
                  <el-form-item label="当前账号：" prop="name">
                    <el-input type="text" v-model.trim="userAndName" disabled>{{
                      userAndName
                    }}</el-input>
                  </el-form-item>
                  <el-form-item label="密保手机号：" prop="tel">
                    <el-input type="text" v-model.trim="phone" disabled>{{
                      phone
                    }}</el-input>
                  </el-form-item>
                  <el-form-item
                    label="验证码："
                    prop="vscode"
                    class="vscodeInput"
                  >
                    <el-input
                      type="text"
                      v-model.trim="telForm.vscode"
                      placeholder="输入验证码"
                      clearable
                    ></el-input>
                    <el-button
                      class="vscodeBtn fontBorderTheme fontColorTheme"
                      type="primary"
                      size="medium"
                      v-show="!isCount"
                      @click="getVscode()"
                      :disabled="canClick"
                      >获取验证码</el-button
                    >
                    <el-button
                      type="info"
                      plain
                      size="medium"
                      v-show="isCount"
                      disabled
                      >{{ countDownTime }}s后重新获取</el-button
                    >
                  </el-form-item>
                  <el-form-item label="新手机号：" prop="newTel">
                    <el-input
                      type="text"
                      v-model.trim="telForm.newTel"
                      placeholder="输入新密保手机号"
                      clearable
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="确认新手机号：" prop="newTelToo">
                    <el-input
                      type="text"
                      v-model.trim="telForm.newTelToo"
                      placeholder="再次输入新密保手机号"
                      clearable
                    ></el-input>
                  </el-form-item>
                  <el-form-item style="margin-top: 40px">
                    <el-button
                      style="margin-left: 47px"
                      type="primary"
                      size="medium"
                      class="commonBut saveBtn"
                      @click="submitTelForm()"
                      :loading="canUpdate"
                      >保存修改</el-button
                    >
                    <el-button
                      size="medium"
                      class="cancelBtn"
                      @click="cancelSubmit('telForm')"
                      >取消</el-button
                    >
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-collapse-transition>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import changePW from '@/components/enterpriseSet/changePassword'

export default {
  name: 'setPassword',
  components: {
    changePW,
  },
  data() {
    //验证手机号
    var validateTel1 = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('新手机号不能为空'))
      } else {
        var regTel = /^1[3456789]\d{9}$/
        if (!regTel.test(value)) {
          callback(new Error('手机号码格式不正确'))
        } else {
          if (this.telForm.newTelToo !== '') {
            this.$refs.telForm.validateField('newTelToo')
            callback()
          }
        }
      }
    }
    var validateTel2 = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('新手机号不能为空'))
      } else {
        var regTel = /^1[3456789]\d{9}$/
        if (!regTel.test(value)) {
          callback(new Error('手机号码格式不正确'))
        } else {
          if (value != this.telForm.newTel) {
            callback(new Error('两次手机号输入不一致'))
          }
          callback()
        }
      }
    }
    //验证短信验证码
    var validateVsode = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('验证码不能为空'))
      } else {
        var url = 'api-bs/message/base/checkvc'
        var data = {
          tel: this.telphone,
          vc: this.telForm.vscode,
        }
        this.axios({
          method: 'post',
          url: url,
          data: data,
        }).then(
          (res) => {
            if (!res.data.hasError) {
              callback()
            } else {
              callback(new Error(res.data.errorMsg))
            }
          },
          (response) => {
            callback(new Error('验证失败'))
          }
        )
      }
    }
    return {
      titleText: '账号设置',
      type: '', //修改手机号还是密码
      showQy: false, //是否展示企业设置
      loginType: 'QY', //默认登录类型
      userName: '', //账号名
      companyName: '', //公司名
      userAndName: '',
      telphone: '', //未脱敏旧手机号
      phone: '', //手机号
      updatePass: false,
      updateTel: false,
      canClick: false, //不可以点击获取验证码
      isCount: false, //短信验证码
      countDownTime: 60, //倒计时
      canSubmit: false, //是否可以提交
      canUpdate: false, //是否可以提交修改手机号
      // passwordRule: {
      //   oldPass: [
      //     { required: true, validator: validateOldPass, trigger: "blur" },
      //   ],
      //   newPass: [
      //     { required: true, validator: validatePass1, trigger: "blur" },
      //   ],
      //   checkPass: [
      //     { required: true, validator: validatePass2, trigger: "blur" },
      //   ],
      // },
      // passwordForm: {
      //   oldPass: "",
      //   newPass: "",
      //   checkPass: "",
      // },
      telRule: {
        vscode: [{ required: true, validator: validateVsode, trigger: 'blur' }],
        newTel: [{ required: true, validator: validateTel1, trigger: 'blur' }],
        newTelToo: [
          { required: true, validator: validateTel2, trigger: 'blur' },
        ],
      },
      telForm: {
        tel: '',
        vscode: '',
        newTel: '',
        newTelToo: '',
      },
      isShowUpdate: true,
      pwLevel: '', //密码强度
      isShowUser: true,
    }
  },
  watch: {
    $route(to, from) {
      this.showForm()
      //获取页面信息
      //   this.getInfo();
    },
  },
  created() {
    //判断用户类型
    // this.loginType = localStorage.getItem('loginType');
    // if(this.loginType === 'QY'){
    //     this.showQy = true;
    // }else{
    //     this.showQy = false;
    // };

    this.showForm()

    //获取页面信息
    // this.getInfo();

    // console.log(this.loginType)
    // this.isShowUpdate = this.$store.state.buttonLimitsArr.indexOf('myaccount:update') > -1;
    //未脱敏手机号
    this.telphone = this.$store.state.userTel
    //脱敏手机号
    if (this.telphone) {
      this.phone =
        this.telphone.substring(0, 3) +
        '****' +
        this.telphone.substring(this.telphone.length - 4)
    }
    this.userAndName = this.$store.state.usernameAndType
  },
  methods: {
    //根据修改类型显示不同的修改表单
    showForm() {
      this.type = this.$route.query.type
      if (this.type === 'tel') {
        this.updatePass = false
        this.updateTel = true
      }
      if (this.type === 'password') {
        this.updatePass = true
        this.updateTel = false
      }
    },
    //修改密码
    updatePassword() {
      this.updatePass = true
      this.updateTel = false
      this.canSubmit = false
      // this.$nextTick(function () {
      //   this.$refs.passwordForm.resetFields();
      // });
    },
    //修改手机号
    updateTelEvent() {
      this.updatePass = false
      this.updateTel = true
      this.canUpdate = false
      this.$nextTick(function () {
        this.$refs.telForm.resetFields()
      })
    },
    //获取页面信息
    getInfo() {
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-u/useraccount',
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              var data = res.data.result
              vm.userName = data.username
              vm.companyName = data.nickname
              vm.telphone = data.tel
              vm.userAndName = vm.userName + '(' + vm.companyName + ')'
              var tel =
                vm.telphone.substring(0, 3) +
                '****' +
                vm.telphone.substring(vm.telphone.length - 4)
              vm.phone = tel
            }
          },
          (response) => {
            this.$message({
              showClose: true,
              duration: 0,
              message: '获取账号信息失败',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    //发送验证码倒计时
    countDown() {
      let vm = this
      //开启倒计时
      vm.isCount = true
      var auth_timetimer = setInterval(() => {
        vm.countDownTime--
        if (vm.countDownTime <= 0) {
          vm.isCount = false
          clearInterval(auth_timetimer)
          vm.countDownTime = 60
        }
      }, 1000)
    },
    //发送短信验证码
    getVscode() {
      this.canClick = true
      //验证码倒计时
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-bs/message/base/sendvc',
        data: {
          tel: vm.telphone,
        },
      })
        .then(
          (res) => {
            vm.canClick = false
            //已发送验证码
            if (!res.data.hasError) {
              this.$message({
                showClose: true,
                message: '验证码已发送至您的旧手机',
                type: 'success',
              })
              //验证码倒计时
              this.countDown()
            } else {
              this.$message({
                showClose: true,
                duration: 0,
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.$message({
              showClose: true,
              duration: 0,
              message: '发送验证码失败',
              type: 'error',
            })
            vm.canClick = false
          }
        )
        .catch((error) => {
          vm.canClick = false
        })
    },
    // //密码修改成功后自动退出该账号并跳转至登录页面；
    // logout() {
    //   var vm = this;
    //   vm.axios({
    //     method: "get",
    //     url: "api-u/sys/logout?Authorization=" + localStorage.getItem("access_token"),
    //   })
    //     .then(
    //       (res) => {
    //         //清除token
    //         localStorage.setItem("access_token", "");
    //         localStorage.setItem("refresh_token", "");
    //         localStorage.setItem("userName", "");
    //         vm.$router.replace("/login/loginNext?type=" + this.loginType);
    //       },
    //       (res) => {
    //         localStorage.setItem("access_token", "");
    //         localStorage.setItem("refresh_token", "");
    //         localStorage.setItem("userName", "");
    //         vm.$router.replace("/login/loginNext?type=" + this.loginType);
    //       }
    //     )
    //     .catch((error) => {});
    // },
    //修改密码保存
    // submitPassForm2() {
    //   let vm = this;
    //   vm.$refs["passwordForm"].validate((valid) => {
    //     if (valid) {
    //       vm.canSubmit = true;
    //       vm.axios({
    //         method: "post",
    //         url: "api-u/users/editpassword",
    //         data: {
    //           password: vm.passwordForm.newPass,
    //         },
    //       })
    //         .then(
    //           (res) => {
    //             vm.canSubmit = false;
    //             this.$message({
    //               showClose: true,
    //               message: "密码修改成功,请重新登录",
    //               type: "success",
    //             });
    //             this.logout();
    //           },
    //           (response) => {
    //             this.$message({
    //               showClose: true,
    //               duration: 0,
    //               message: "修改失败",
    //               type: "error",
    //             });
    //             vm.canSubmit = false;
    //           }
    //         )
    //         .catch((error) => {});
    //     } else {
    //       vm.canSubmit = false;
    //       return false;
    //     }
    //   });
    // },
    //提交修改手机号
    submitTelForm() {
      let vm = this
      vm.canUpdate = true
      var data = {}
      var url = ''
      // 接口平台
      if (localStorage.getItem('loginType') == 'DT') {
        url = 'api-m/inputUser/base/v1/updateTel'
        data = {
          id: this.$store.state.userId, //----用户id
          tel: vm.telForm.newTel,
        }
      } else {
        url = 'api-u/usertel'
        data = {
          vc: vm.telForm.vscode,
          tel: vm.telphone,
          newTel: vm.telForm.newTel,
        }
      }
      vm.$refs['telForm'].validate((valid) => {
        if (valid) {
          vm.axios({
            method: 'post',
            url,
            data,
          }).then(
            (res) => {
              if (!res.data.hasError) {
                this.$message({
                  showClose: true,
                  message: '手机号修改成功',
                  type: 'success',
                })
                this.$store.state.userTel = vm.telForm.newTel
                vm.telphone = this.$store.state.userTel
                // vm.telphone = vm.telForm.newTel;
                vm.phone =
                  vm.telphone.substring(0, 3) +
                  '****' +
                  vm.telphone.substring(vm.telphone.length - 4)
                vm.updateTel = false
                //清空表单
                vm.telForm.vscode = ''
                vm.telForm.newTel = ''
                vm.telForm.newTelToo = ''
              } else {
                this.$message({
                  showClose: true,
                  duration: 0,
                  message: res.data.errorMsg,
                  type: 'error',
                })
              }
              vm.canUpdate = false
            },
            (response) => {
              this.$message({
                showClose: true,
                duration: 0,
                message: '修改失败',
                type: 'error',
              })
              vm.canUpdate = false
            }
          )
        } else {
          vm.canUpdate = false
        }
      })
    },
    //取消修改
    cancelSubmit(formName) {
      this.updateTel = false
      // 取消
      this.$refs[formName].resetFields()
    },
    cancelSubmitChange() {
      this.updatePass = false
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  .el-divider {
    margin: 24px 0 !important;
  }
  // position: absolute;
  // padding: 24px;
  // top: 106px;
  // bottom: 0px;
  // left: 0px;
  // right: 0px;
  // overflow-y: auto;
  // overflow-x: hidden;
  .blockTitle {
    height: 66px;
    line-height: 46px;
    padding: 10px 24px;
    background-color: #e4ebf1;
    font-size: 18px;
    font-weight: bold;
  }
  .passwordForm,
  .telForm {
    transform: translateX(-60px);
    width: 500px;
    margin: 50px auto;
    transform: translateX(-60px);
    .vscodeInput {
      .el-input {
        width: 220px;
        margin-right: 10px;
      }
    }
  }
  .btnBox {
    text-align: center;
  }
  .mainCon {
    padding: 24px;
    height: calc(100% - 67px);
    .updateItem {
      width: 108px;
      height: 36px;
      text-align: center;
      color: #fff;
      font: bold 14px/36px Microsoft YaHei;
      background-color: #02a2aa;
    }
    .backYellow {
      background-color: #f9a243;
    }
    .itemBox {
      padding-left: 24px;
      margin-top: 20px;
      font-size: 14px;
      .itemValue {
        color: #666;
      }
    }
    .el-button--primary {
      background-color: #009588;
      border-color: #009588;
      color: #fff;
    }
  }
}
.editBox {
  border: 1px solid #f1f1f1;
  border-radius: 5px;
  padding: 20px 24px;
  margin-bottom: 20px;
  &Btn {
    text-align: right;
    .miniButColor {
      height: 36px;
      margin-top: 20px;
      border-radius: 4px !important;
    }
  }
}
/deep/.el-divider {
  background-color: rgba(220, 223, 230, 0.4) !important;
}
.opetareText {
  line-height: 18px;
}
.vscodeBtn {
  width: 136px;
  border: 1px solid #009588;
  color: #009588;
  margin-left: 10px;
  background-color: #fff !important;
}
</style>
